package com.njupt.blog.webapp.action;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.convention.annotation.Result;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import org.springframework.util.StringUtils;
import org.xml.sax.SAXException;

import com.njupt.blog.model.Article;
import com.njupt.blog.model.ArticleComment;
import com.njupt.blog.model.Blog;
import com.njupt.blog.model.Media;
import com.njupt.blog.model.Tag;
import com.njupt.blog.model.TagMark;
import com.njupt.blog.model.TopStep;
import com.njupt.dao.PaginationSupport;
import com.njupt.service.BaseAction;
import com.njupt.service.GenericPaginationManager;
import com.njupt.user.model.UploadFile;
import com.njupt.user.model.User;
import com.njupt.utils.HttpsClientTmp;
import com.njupt.utils.RequestUtils;
import com.opensymphony.xwork2.Preparable;
import com.njupt.blog.model.StatVisitor;

/**
 * @author yun
 *
 */

@ParentPackage(value="blog")
@Results({
	@Result(name="projectIndex", location="/blog/projectIndex.jsp"),
	@Result(name = "blogIndex", location = "/blog/blogIndex.jsp"),
	@Result(name = "index", location = "/index.jsp"),
	@Result(name = "articleIndex", location = "/blog/articleIndex.jsp"),
	@Result(name = "personalArticles", location = "/blog/personalArticles.jsp"),
	@Result(name = "article", location = "/blog/article.jsp"),
	@Result(name = "manageArticles", location = "/blog/manageArticles.jsp"),
	@Result(name = "blogDescription", location = "/blog/blogDescription.jsp"),
	@Result(name = "newArticleForm", location = "/blog/newArticleForm.jsp"),
	@Result(name = "articleEditForm", location = "/blog/articleEditForm.jsp"),
	@Result(name = "newBlogForm", location = "/blog/newBlogForm.jsp"),
	@Result(name = "blogEditForm", location = "/blog/blogEditForm.jsp"),
	@Result(name = "newBlogForm", location = "/blog/newBlogForm.jsp"),
	@Result(name = "blogEditForm", location = "/blog/blogEditForm.jsp")
})
public class BlogAction extends BaseAction implements Preparable {
	private GenericPaginationManager<Blog, Long> blogManager;
	private GenericPaginationManager<Article, Long> articleManager;
	private GenericPaginationManager<User, Long> userManager;
	private Blog blog;
	private Article article;
	private PaginationSupport blogPagination;
	private PaginationSupport articlePagination;
	private PaginationSupport articleCommentPagination;
	private Long[] blogIds;
	private Long blogId;
	private String bloggerName;
	private Long articleId;
	private Long creatorId;
	private Long blogerId;
	private String userId;
	private String attachIdsStr; //是否包含附件
	String allTagNames;//创建文章时添加的标签
	Long previousArticleId,nextArticleId;//上下博文的ID
	private List<Article> statarticles = new ArrayList<Article>();
	private List<Long> articleIds;//记录你所关注的所有博文
	private ArticleComment articleComment;//文章的评论
	private int pageSize = 30;
	
	private TopStep topStep;
	
	private String userFacesCn[] = { "微笑", "撇嘴", "色", "发呆", "得意", "流泪", "害羞",
			"闭嘴", "睡", "大哭", "尴尬", "发怒", "调皮", "呲牙", "惊讶", "难过", "酷", "冷汗",
			"抓狂", "吐", "偷笑", "可爱", "白眼", "傲慢", "饥饿", "困", "惊恐", "流汗", "憨笑",
			"大兵", "奋斗", "咒骂", "疑问", "嘘...", "晕", "折磨", "衰", "骷髅", "敲打", "再见",
			"擦汗", "抠鼻", "鼓掌", "糗大了", "坏笑", "左哼哼", "右哼哼", "哈欠", "鄙视", "委屈",
			"快哭了", "阴险", "亲亲", "吓", "可怜", "菜刀", "西瓜", "啤酒", "篮球", "乒乓", "咖啡",
			"饭", "猪头", "玫瑰", "凋谢", "示爱", "爱心", "心碎", "蛋糕", "闪电", "炸弹", "刀",
			"足球", "瓢虫", "便便", "月亮", "太阳", "礼物", "拥抱", "强", "弱", "握手", "胜利",
			"抱拳", "勾引", "拳头", "差劲", "爱你", "NO", "OK", "爱情", "飞吻", "跳跳", "发抖",
			"怄火", "转圈", "磕头", "回头", "跳绳", "挥手", "激动", "街舞", "献吻", "左太极", "右太极",
			"吃惊", "再见", "飘过", "打住", "justSOSO", "开玩笑..", "打扮", "天然呆", "幽灵附体",
			"就是YOU", "没门儿", "看穿你", "嘻嘻色", "sorry", "休息..", "睡觉了", "捣蛋", "起飞",
			"清醒一下", "洗澡", "起飞", "阿里特战队", "穿内裤", "爱神阿里", "好垫背", "阿里Jackson",
			"英雄", "go!!", "甩卖", "眼保健操", "健身", "做做运动", "无聊", "学习..", "0分啊，0分",
			"好难过", "思考" };

	private String userFacesEn[] = { "pic_1", "pic_2", "pic_3", "pic_4",
			"pic_5", "pic_6", "pic_7", "pic_8", "pic_9", "pic_10", "pic_11",
			"pic_12", "pic_13", "pic_14", "pic_15", "pic_16", "pic_17",
			"pic_18", "pic_19", "pic_20", "pic_21", "pic_22", "pic_23",
			"pic_24", "pic_25", "pic_26", "pic_27", "pic_28", "pic_29",
			"pic_30", "pic_31", "pic_32", "pic_33", "pic_34", "pic_35",
			"pic_36", "pic_37", "pic_38", "pic_39", "pic_40", "pic_41",
			"pic_42", "pic_43", "pic_44", "pic_45", "pic_46", "pic_47",
			"pic_48", "pic_49", "pic_50", "pic_51", "pic_52", "pic_53",
			"pic_54", "pic_55", "pic_56", "pic_57", "pic_58", "pic_59",
			"pic_60", "pic_61", "pic_62", "pic_63", "pic_64", "pic_65",
			"pic_66", "pic_67", "pic_68", "pic_69", "pic_70", "pic_71",
			"pic_72", "pic_73", "pic_74", "pic_75", "pic_76", "pic_77",
			"pic_78", "pic_79", "pic_80", "pic_81", "pic_82", "pic_83",
			"pic_84", "pic_85", "pic_86", "pic_87", "pic_88", "pic_89",
			"pic_90", "pic_91", "pic_92", "pic_93", "pic_94", "pic_95",
			"pic_96", "pic_97", "pic_98", "pic_99", "pic_100", "pic_101",
			"pic_102", "pic_103", "pic_104", "pic_105", "pic_106", "pic_107",
			"pic_108", "pic_109", "pic_110", "pic_111", "pic_112", "pic_113",
			"pic_114", "pic_115", "pic_116", "pic_117", "pic_118", "pic_119",
			"pic_120", "pic_121", "pic_122", "pic_123", "pic_124", "pic_125",
			"pic_126", "pic_127", "pic_128", "pic_129", "pic_130", "pic_131",
			"pic_132", "pic_133", "pic_134", "pic_135", "pic_136", "pic_137",
			"pic_138", "pic_139", "pic_140", "pic_141", "pic_142" };
	
	@Override
	public void prepare() throws Exception {
		blogId = (Long) RequestUtils.getObject(getRequest(), "blogId", Long.class);
		articleId = (Long) RequestUtils.getObject(getRequest(), "articleId", Long.class);
		if(blogId != null){
			blog = blogManager.get(blogId);
		}
		if(articleId != null){
			article = articleManager.get(articleId);
		}

	}
	/**
	 * 根据文章名 搜索文章的方法。
	 */
	public String articleSearch(){
			DetachedCriteria dc = DetachedCriteria.forClass(Article.class);
	    	    			//标题
			String name = (String) this.getParameter("q_articleName", String.class);
			if(name != null && !"".equals(name)){
				dc.add(Restrictions.like("title", "%"+name+"%"));
			}
	  	    	    	    	    	    	    	    	  
			articlePagination = articleManager.paginateByCriteria(
					dc, pageNo, pageSize
			);
			if(conditionStr == null)
			conditionStr = composePaginationSearchQueryString();
			return "manageArticles";
	}
	/**
	 * 知识库的文章首页 --显示与标签相关的articles
	 * @return
	 */
	public String articleTag() {
		String hql = "from Article where draft = 1  and blogId in " +
				"(select id from Blog where ifPersonal='1')";
		String tag = (String) this.getParameter("tag", String.class);
		if (tag != null && tag.length() > 0) {
			List<Long> blogIds = manager
					.find("select relateEntityId from TagMark where tagName = ?",
							new Object[] { tag });
			int length = blogIds.size();
			if (length > 0) {
				hql = hql + " and id in (";
				for (Long blogId : blogIds) {
					if (length == 1)
						hql = hql + blogId;
					else {
						hql = hql + blogId + ",";
						length--;
					}
				}
				hql = hql + ")";
			}
		}
		
		hql = hql + " order by creationDate desc";
		articlePagination = articleManager.paginateByHql(hql, pageNo, pageSize,null);
		if (conditionStr == null) {
			conditionStr = composePaginationSearchQueryString();
		}
		return "articleIndex";
	}
	/*
	 * blog的删除
	 */
	public  void ajaxDeleteBlog(){  //参考sql:delete from t_weibo_reply  where f_id=23 删除博客
		Long currentUserId = Long.parseLong(getCurrentUser().getId()+"");
		String blogId = (String) this.getParameter("blogId", String.class);
		Long userId = Long.parseLong((String)this.getParameter("userId", String.class));
		//传递给前台一些ajax数据
		 JSONObject json = new JSONObject();
		 if(!(currentUserId.equals(userId)))  json.put("result", "No Permission");
		 else{
			 String sqlc = "delete from t_article_comment where f_article_id  in (select f_id from t_article where f_blog_id ="+blogId+")";
			 manager.executeUpdateByNativeSql(sqlc,null);
			 String sqlm = "delete from t_article where f_blog_id ="+blogId;
			 manager.executeUpdateByNativeSql(sqlm,null);
			 String sql = "delete from t_blog where f_id="+blogId;
			 int cnt = manager.executeUpdateByNativeSql(sql,null);
			 if( cnt > 0 )  json.put("result", "Success");
		 }
		 responseWrite(json.toString());
	}
	//知识库界面的删除文章
	public  void ajaxDeleteArticle(){  //参考sql:delete from t_weibo_reply  where f_id=23
		Long currentUserId = Long.parseLong(getCurrentUser().getId()+"");
		String articleId = (String) this.getParameter("articleId", String.class);
		Long userId = Long.parseLong((String)this.getParameter("userId", String.class));
		//传递给前台一些ajax数据
		 JSONObject json = new JSONObject();
		 if(!(currentUserId.equals(userId)))  json.put("result", "No Permission");
		 else{
			 //先删除评论 ，
			 String sqlc = "delete from t_article_comment where f_article_id="+articleId;
			  manager.executeUpdateByNativeSql(sqlc,null);
			 String sql = "delete from t_article where f_id="+articleId;
			 manager.executeUpdateByNativeSql(sql,null);
			 sql="delete from t_tag_mark where f_relate_entity_id="+articleId;
			 int cnt=manager.executeUpdateByNativeSql(sql,null);
			 if( cnt > 0 )  json.put("result", "Success");
		 }
		 responseWrite(json.toString());
	}
	/*
	 * 保存顶和踩 
	 */
	public void saveTS(){
		Date date = new Date();
		topStep.setActionDate(date);
		topStep = (TopStep) manager.save(topStep);
	}
	/*
	 * 保存博文的回复功能
	 */
	public void saveArticleComment() throws IOException {
//		data:{articleId:articleId,articleCommentContent:articleCommentContent,"method:saveArticleComment":"www"}
			ArticleComment   act = new  ArticleComment();
			act.setCreatorId(this.getCurrentUser().getId());
			act.setCreator(this.getCurrentUsername());
			Date date = new Date();
			act.setCreationDate(new java.sql.Date(date.getTime()));
			String articleCommentContent =  (String)RequestUtils.getObject(getRequest(), "articleCommentContent", String.class);
			act.setArticleId(articleId);
			
			/*瀵筩ontent 杩涜澶勭悊*/
			articleCommentContent = articleCommentContent.replace("\n", "<br/>");
			
			act.setContent(articleCommentContent);
		    act = (ArticleComment)manager.save(act);
		    
		    DateFormat f3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String creationDateTo = f3.format(act.getCreationDate()).toString();
			HttpServletResponse  response = ServletActionContext.getResponse();
			response.setContentType("text/html");
			response.setCharacterEncoding("UTF-8");
			response.getWriter().write("{articleCommentId:"+act.getId()+",creationDate:'"+creationDateTo+"',articleCommentContent:'"+act.getContent().replace('\'', '\"')+"'}");
   }
	/*
	 * 保存博文的回复功能
	 */
	public void saveArticleComment2() throws IOException {
	Date date = new Date();
	articleComment.setCreationDate(new java.sql.Date(date.getTime()));
	articleComment.setCreator(this.getCurrentUsername());
	articleComment.setCreatorId(this.getCurrentUser().getId());
	articleComment.setArticleId(article.getId());
	String content = articleComment.getContent();
	content = content.replace("<", "&lt;").replace(">", "&gt;");
	content = regexReplace("(http://\\S{9,3000})( |;|；|，|,|。)",
			"<a target = '_blank' href='$1'>$1</a>", content); // 遇到网址特殊处理一下就可以了,以http://开头，以,；空格结束
	for (int i = 0; i < userFacesCn.length; i++) {
		content = regexReplace("\\[" + userFacesCn[i] + "\\]", "\\["
				+ userFacesEn[i] + "\\]", content);
	}
	content = regexReplace("\\[(\\S{5,7})\\]",
			"<img src='" + getRequest().getContextPath()
					+ "/img/faces/$1.gif'></img>", content);
	content = content.replace("\n", "<br/>");
	articleComment.setContent(content);
	articleComment = (ArticleComment) manager.save(articleComment);
	JSONObject json = new JSONObject();
	DateFormat f3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	String creationDateTo = f3.format(articleComment.getCreationDate())
			.toString();
	if(articleComment.getParentCommentId()!=null){
		json.put("parentCommentId", articleComment.getParentCommentId());
	}
	json.put("articleCommentId", articleComment.getId());
	json.put("creationDate", creationDateTo);
	json.put("articleCommentContent", articleComment.getContent());
	responseWrite(json.toString());
}
	
	/*
	 * 保存视频的功能
	 */
	public void saveVideo() throws IOException, SAXException, ParserConfigurationException{
     // { "apiU": apiU,"url":url,"method:saveVideo":"xxxx","description":"博文视频地址的解析" }
	 HttpServletResponse  response = ServletActionContext.getResponse();
	 HttpServletRequest  request = ServletActionContext.getRequest();
	 String apiU = (String)request.getParameter("apiU");
	 String urlp = (String)request.getParameter("url");
	 String htmlUrl = apiU + urlp ;
	 URL url = new URL(htmlUrl);
	 URLConnection urlcon = url.openConnection();
	 urlcon.connect();//打开通信资源链接
	 InputStream in = urlcon.getInputStream();
     in = new BufferedInputStream(in);
     StringBuffer buff = new StringBuffer();
     InputStreamReader r = new InputStreamReader(in, "Utf-8");   //进行字符编码的设置，从而解决中文乱码的问题
     int c;
     while ((c = r.read()) != -1)
     {
       buff.append((char)c);
     }
     in.close();
     r.close();
     String outputData = buff.toString();   
     
     JSONArray arrRes = JSONArray.fromObject("["+outputData+"]");
     JSONObject json = arrRes.getJSONObject(0);
     JSONObject multiResult = json.getJSONObject("repasteInfo");
     JSONObject res = multiResult.getJSONObject("itemInfo");     
	 
	 Media media = new Media();
	 media.setTitle(res.getString("title"));
	 media.setThumbnail(res.getString("picUrl"));
	 String  htmlCode = "<embed src=\""+res.getString("outerPlayerUrl")+"\" allowFullScreen=" +
	    		"\"true\" quality=\"high\" width=\"480\" height=\"400\" align=\"middle\" allowScriptAccess=\"always\" type=\"application/x-shockwave-flash\"></embed>";
	 media.setHtmlCode(htmlCode);
	 media.setCreateTime((new Date()));
	 media.setType(2);
	 media = (Media)manager.save(media);
	 
	 response.setContentType("text/html");
     response.setCharacterEncoding("UTF-8");
     response.getWriter().print("{status:'Success',mediaType:2,videoId:"+media.getId()+",title:'"+res.getString("title")+"'}");
 
	}
	//保存优酷视频
	public void saveYoukuVideo() throws Exception{
		String apiU = (String) this.getParameter("apiU", String.class);
		String url = (String) this.getParameter("url", String.class);
		Map<String, String> params = new HashMap<String, String>();
		params.put("client_id", "903abe2d17d70056");
		params.put("video_url", url);
		String str = HttpsClientTmp.post(apiU,params);
		JSONArray arrRes = JSONArray.fromObject("["+str+"]");
		JSONObject json = arrRes.getJSONObject(0);
		Media media = new Media();
		media.setTitle(json.getString("title"));
		media.setThumbnail(json.getString("thumbnail"));
		String htmlCode = "<embed src=\""
				+ json.getString("player")
				+ "\" allowFullScreen="
				+ "\"true\" quality=\"high\" width=\"480\" height=\"400\" align=\"middle\" allowScriptAccess=\"always\" type=\"application/x-shockwave-flash\"></embed>";
		media.setHtmlCode(htmlCode);
		media.setCreateTime((new Date()));
		media.setType(2);
		media = (Media)manager.save(media);
		responseWrite("{status:'Success',mediaType:2,videoId:"+media.getId()+",title:'"+json.getString("title")+"'}");
	}
	
	public void saveMusic() throws IOException{
		//"title": $(this).attr("name"),"htmlCode":'',"method:saveMusic":"xxxx","description":"音乐信息的存储" 
		 HttpServletResponse  response = ServletActionContext.getResponse();
		 HttpServletRequest  request = ServletActionContext.getRequest();
		 String title = (String)request.getParameter("title");
		 String htmlCode = (String)request.getParameter("htmlCode");
		 Media media = new Media();
		 media.setTitle(title);
		 media.setThumbnail(null);
		 media.setHtmlCode(htmlCode);
		 media.setCreateTime((new Date()));
		 media.setType(1);
		 media = (Media)manager.save(media);
		
		 response.setContentType("text/html");
	     response.setCharacterEncoding("UTF-8");
	     response.getWriter().print("{status:'Success',mediaType:1,musicId:"+media.getId()+"}");
	}
	
	
	/**
	 * 保存文章。
	 * @return
	 * @throws JSONException 
	 */
	public String saveArticle() {
		HttpServletResponse  response = ServletActionContext.getResponse();
		HttpServletRequest  request = ServletActionContext.getRequest();
		int articleFrom = new Integer((String)request.getParameter("articleFrom")).intValue();
	    article.setType(articleFrom);
	    
		String saveType = (String) this.getParameter("method:saveArticle",String.class);
		Date now = new Date();
		User me = getCurrentUser();
		article.setCreationDate(now);
		article.setCreatorId(me.getId());
		article.setCreatorName(me.getUsername());
		if (article.getBlogId() == null) {
			throw new RuntimeException("哥们，你这是。。。。。");
		}
		article.setBlogId(article.getBlogId());
		if (null == article.getCreationDate())
			article.setCreationDate(new Date());
		else
			article.setModificationDate(new Date());
		if (!StringUtils.hasText(article.getTitle())) {
			throw new RuntimeException("哥们，你这是。。。。。");
		}
		article = articleManager.save(article);
		saveBlogTag(article);
		
		switch (articleFrom) {
		case 1:   //如果来自音乐 
			String musicJson = (String)request.getParameter("musicJson");
			
			if(musicJson == null || "".equals(musicJson) || musicJson.equals("-1")){}
			else{
			JSONArray arrRes1 = JSONArray.fromObject("["+musicJson+"]");
        	int m1 = 0;
        	JSONObject  json1 ;
        	for(;  m1 < arrRes1.size(); m1++){
        		json1 = (JSONObject)arrRes1.get(m1); 
        		Long musicId = json1.getLong("musicId");
        		Media media1 = (Media) manager.get(Media.class,musicId);
    			media1.setArticleId(article.getId());
    			manager.save(media1);
        	}
			}
			
			break;
       
		case 2:  //如果来自视频
			String videoJson = (String)request.getParameter("videoJson");
			
			if(videoJson == null || "".equals(videoJson) || videoJson.equals("-1")){}
			else{
			JSONArray arrRes2 = JSONArray.fromObject("["+videoJson+"]");
        	int m2 = 0;
        	JSONObject  json2 ;
        	for(;  m2 < arrRes2.size(); m2++){
        		json2 = (JSONObject)arrRes2.get(m2); 
        		Long videoId = json2.getLong("videoId");
        		Media media2 = (Media) manager.get(Media.class,videoId);
    			media2.setArticleId(article.getId());
    			manager.save(media2);
        	}
			}
			break;
			
        case 3: //如果来自图片
        	String pictureJson = (String)request.getParameter("pictureJson");   //{'fileId':59},{'fileId':60}
			
        	if(pictureJson == null || "".equals(pictureJson) || pictureJson.equals("-1")){}
			else{
        	JSONArray arrRes3 = JSONArray.fromObject("["+pictureJson+"]");
        	int m3 = 0;
        	JSONObject  json3 ;
        	for(;  m3 < arrRes3.size(); m3++){
        		json3 = (JSONObject)arrRes3.get(m3); 
        		Long fileId = json3.getLong("fileId");
    			UploadFile upf = (UploadFile) manager.get(UploadFile.class,fileId);
    			upf.setArticleId(article.getId());
    			manager.save(upf);
        	}
			}
	       break;
	       
        case 4: //如果来自普通文字
	
	       break;
		default:
			break;
		}
	
		return "index";
	}
	//删除文章的评论
	public  void ajaxDeleteArticleComment(){  //参考sql:delete from t_weibo_reply  where f_id=23
		Long currentUserId = Long.parseLong(getCurrentUser().getId()+"");
		Long articlecommentId = (Long) this.getParameter("articlecommentId", Long.class);
		Long userId = Long.parseLong((String)this.getParameter("userId", String.class));
		//传递给前台一些ajax数据
		 JSONObject json = new JSONObject();
		 if(!(currentUserId.equals(userId)))  json.put("result", "No Permission");
		 else{
			 String sql = "delete from t_article_comment where f_id="+articlecommentId+" or f_parent_comment_id="+articlecommentId;
			 int cnt = manager.executeUpdateByNativeSql(sql,null);
			 if( cnt > 0 )  json.put("result", "Success");
		 }
		 responseWrite(json.toString());
	}
	//删除二次评论的方法
	public  void ajaxDeleteReArticleComment(){  //参考sql:delete from t_weibo_reply  where f_id=23
		Long currentUserId = Long.parseLong(getCurrentUser().getId()+"");
		Long rarticlecommentId = (Long) this.getParameter("rarticlecommentId", Long.class);
		Long userId = Long.parseLong((String)this.getParameter("userId", String.class));
		//传递给前台一些ajax数据
		 JSONObject json = new JSONObject();
		 if(!(currentUserId.equals(userId)))  json.put("result", "No Permission");
		 else{
			 String sql = "delete from t_article_comment where f_id="+rarticlecommentId;
			 int cnt = manager.executeUpdateByNativeSql(sql,null);
			 if( cnt > 0 )  json.put("result", "Success");
		 }
		 responseWrite(json.toString());
	}
	/**
	 * 新增博客的界面。
	 * @return
	 */
	public String newBlogForm(){
		User me = getCurrentUser();
		blog = new Blog();
		blog.setManagerId(me.getId());
		blog.setManagerName(me.getUsername());
		return "newBlogForm";
	}
	/**
	 * 修改博客的表单页面。
	 * 
	 * @return
	 */
	public String blogEditForm() {
		User me = getCurrentUser();
		if (!blog.getManagerId().equals(me.getId())) {
			throw new RuntimeException("哥们，你这是。。。。。");
		}
			return "blogEditForm";
		}
	/**
	 * 保存博客。
	 * @return
	 */
	public String saveBlog() {
		Date now = new Date();
		User me = getCurrentUser();
		blog.setCreationDate(now);
		blog.setManagerId(me.getId());
		blog.setManagerName(me.getUsername());
		blog = blogManager.save(blog);
		return "blogIndex";
	}
	/**
	 * 打开一个博客。
	 * @return
	 */
	public String blog(){
		String hql = "from Article where draft = 1 and blogId=? order by creationDate desc";
		articlePagination = articleManager.paginateByHql(hql, pageNo, pageSize,blogId);
		if (conditionStr == null) {
			conditionStr = composePaginationSearchQueryString();
		}
		return "blogIndex";
	}
	
	/**
	 * 打开一篇文章。
	 * @return
	 */
	public String article(){
		if (article != null && this.getCurrentUser() != null
				&& !this.getCurrentUsername().equals(article.getCreatorName())) {
			if (article.getClick() == null)
				article.setClick(1);
			else
				article.setClick(article.getClick() + 1);
			article = (Article) manager.save(article);
		}
		if (article.getCreatorName() != null) articleVisitors();
		String hql = "from ArticleComment where articleId = " + article.getId() 
				+ " and parentCommentId is null order by creationDate desc";
		articleCommentPagination = manager.paginateByHql(hql, pageNo, pageSize,
				null);
		blog = blogManager.get(article.getBlogId());
		return "article";
	}
	
	
	/**
	 * 你可能还喜欢的相关文章 按照:标签相关,博客分类相关,博客相关的顺序查找前10个相关的文章  -----暂时未添加到博客里面
	 */
	public void yLikeRelatedArticle() {
		List<Long> articleIds = new ArrayList<Long>();
		List<String> tagNames = manager
				.find("select tagName from TagMark where relateEntityId = ?",
						new Object[] { articleId });
		if (tagNames.size() > 0) {
			List<Long> ids = manager
					.createCriteria(TagMark.class,
							Restrictions.in("tagName", tagNames.toArray()),
							Restrictions.ne("relateEntityId", articleId))
					.addOrder(Order.desc("recordTime"))
					.setProjection(Projections.groupProperty("relateEntityId"))
					.list();
			if (ids.size() > 0) {
				for (Long id : ids)
					articleIds.add(id);
			}
		}
	}

	/**
	 * 记录本博客相关的标签  -----暂时未添加到博客里面
	 */
	private List<Tag> linkedTags = new ArrayList<Tag>();
	private void linkedTags() {
		List<TagMark> linkedTagMarks = manager.find(
				"from TagMark where  relateEntityId=?",
				new Object[] { article.getId() });
		if (statarticles.size() != 0 && statarticles != null) {
			List<Long> entityIds = new ArrayList<Long>();
			for (Article articleOne : statarticles) {
				if (articleOne != null)
					entityIds.add(articleOne.getId());
			}
			List<TagMark> temps = manager.createCriteria(TagMark.class,
					Restrictions.in("relateEntityId", entityIds.toArray())).list();
			for (TagMark temp : temps)
				if (!linkedTagMarks.contains(temp)) {
					linkedTagMarks.add(temp);
				}
		}
		List<Long> tagIds = new ArrayList<Long>();
		for (TagMark markTemp : linkedTagMarks)
			tagIds.add(markTemp.getTagId());
		if (tagIds.size() > 0) {
			List<Tag> tagTemps = manager.createCriteria(Tag.class,
					Restrictions.in("id", tagIds.toArray())).list();
			for (Tag tagTemp : tagTemps) {
				if (!linkedTags.contains(tagTemp)) {
					linkedTags.add(tagTemp);
				}
			}
		}

	}

	/**
	 * 统计上一篇和下一篇 -----暂时未添加到博客里面
	 */
	public void nextArticle() {
		List<Article> articles = articleManager.find(
				"from Article where blogId = ? order by creationDate asc",
				article.getBlogId());
		List<Article> articlesQ = articleManager.find(
				"from Article where blogId = ? order by creationDate desc",
				article.getBlogId());
		int i = 0;
		for (Article article1 : articles) {
			if (i == 1) {
				nextArticleId = article1.getId();
				break;
			}
			if (article1.getId().equals(article.getId())) {
				i = 1;
			}
		}
		for (Article article1 : articlesQ) {
			if (i == 2) {
				previousArticleId = article1.getId();
				break;
			}
			if (article1.getId().equals(article.getId())) {
				i = 2;
			}
		}
	}
	
	
	/**
	 * 发文章的表单页面。
	 * 
	 * @return
	 */
	public String newArticleForm() {
		article = new Article();
		if(blog !=null)article.setBlogId(blog.getId());
		return "newArticleForm";
	}
	/**
	 * 修改文章的表单页面。
	 * 
	 * @return
	 */
	public String articleEditForm() {
		if (article == null) {
			article = new Article();
		}
		if (blog != null) {
			article.setBlogId(blog.getId());
		}
		return "articleEditForm";
	}
	
	/**
	 * 保存文章内容相关的标签
	 * 
	 * @param typeName
	 * @param blogId
	 */	
	private void saveBlogTag(Article article) {
		Long articleId = article.getId();
		User me = getCurrentUser();
		Date now = new Date();	
		String[] tagArray = article.getTagArray();	
		if(tagArray == null)return;	
		        List<TagMark>articleTagMark=new ArrayList();
		        articleTagMark=manager.find("from TagMark where  relateEntityId ="+ articleId);//查出与当前article关联的所有旧标                
		        int i=0,j=0;
		        //查找新标签
		for(String s:tagArray)
		{
		      if(s.length()==0||s==null)continue;	
		      for(j=0;j<articleTagMark.size();j++) //扫描所有旧标签，看是否有与当前标签相同的旧标签
		      {   
		              if(s.equals(articleTagMark.get(j).getTagName()))
		    	           break;
		      }
		     if(j==articleTagMark.size())  
			 saveTagMark(me, now, articleId, s);
		}
	}	
	
	
	private void saveTagMark(User me, Date now, Long articleId, String tagName) {
		Tag tag = (Tag) manager.queryUniqueResult("from Tag where tagName=?",
				tagName);
		if (tag == null) {
			tag = new Tag();
			tag.setRecordTime(now);
			tag.setTagName(tagName);
			tag.setUserId(me.getId());
			tag.setUsername(me.getUsername());
			tag = (Tag) manager.save(tag);
		}
		TagMark tagMark = new TagMark();
		tagMark.setRecordTime(new java.sql.Date((new Date()).getTime()));
		tagMark.setRelateEntityId(articleId);
		tagMark.setTagName(tagName);
		tagMark.setTagId(tag.getId());
		tagMark.setUserId(me.getId());
		tagMark.setUsername(me.getUsername());
		tagMark = (TagMark) manager.save(tagMark);
	}
	/**
	 * 某个人的所有文章浏览。
	 * @return
	 */
	public String personalArticles() {
		DetachedCriteria dc = DetachedCriteria.forClass(Article.class);
		Long draft = (Long) this.getParameter("draft", Long.class);
		// 显示草稿
		if (draft != null && draft==1) {
				dc.add(Restrictions.eq("draft", 1));
		}
		dc.add(Restrictions.eq("creatorId", blogerId));
		dc.addOrder(Order.desc("creationDate"));
		articlePagination = articleManager.paginateByCriteria(dc, pageNo, pageSize);
		if (conditionStr == null) {
			conditionStr = composePaginationSearchQueryString();
		}
		return "personalArticles";
	}
	/**
	 * 知识库的管理--个人最新博客文章列表 包含文章和文章评论
	 * @return
	 */
	
	public String manageArticles() {
		User me = getCurrentUser();
		blogerId = (Long) this.getParameter("blogerId", Long.class);
		if (blogerId==null || !blogerId.equals(me.getId())) {
			throw new RuntimeException("哥们，你这是。。。。。");
		}else{
				personalArticles();
				return "manageArticles";
			} 
	}
	
	/**
	 * 知识库的管理--个人博客中展示所有文章
	 * @return
	 */
	
	public String blogDescription() {
				blog();
				return "blogDescription";
	}
	/**
	 * 保存该博文最近访问情况   -----暂时未添加到博客里面
	 */
	public void articleVisitors() {
		if (this.getCurrentUsername() != null
				&& !this.getCurrentUsername().equals(article.getCreatorName())) {
			Date now = new Date();
			StatVisitor statvisitor = null;
			int flag = 0;
			List<StatVisitor> visitors = manager.find(
					"from StatVisitor where username = ?",
					new Object[] { this.getCurrentUsername() });
			if (visitors.size() == 0) {
				statvisitor = new StatVisitor();
				statvisitor.setUsername(this.getCurrentUsername());
				statvisitor.setBlogId(article.getBlogId());
				statvisitor.setArticleId(article.getId());
				statvisitor.setVisitimeOfArticle(now);
			} else {
				for (StatVisitor visitor : visitors) {
					if (article.getId().equals(visitor.getArticleId())) {
						statvisitor = (StatVisitor) manager.get(
								StatVisitor.class, visitor.getId());
						statvisitor.setVisitimeOfArticle(now);
						flag = 1;
						break;
					}
				}
				if (flag == 0) {
					for (StatVisitor visitor : visitors) {
						if (visitor.getArticleId() == null) {
							statvisitor = (StatVisitor) manager.get(
									StatVisitor.class, visitor.getId());
							statvisitor.setArticleId(article.getId());
							statvisitor.setBlogId(article.getBlogId());
							statvisitor.setVisitimeOfArticle(now);
							flag = 2;
							break;
						}
					}
					if (flag != 2) {
						statvisitor = new StatVisitor();
						statvisitor.setUsername(this.getCurrentUsername());
						statvisitor.setArticleId(article.getId());
						statvisitor.setBlogId(article.getBlogId());
						statvisitor.setVisitimeOfArticle(now);
					}
				}
			}
			manager.save(statvisitor);
		}
	}
	/*
	 * 保存文章的评论
	 */
	public static String regexReplace(String regex, String repStr,
			String content) {
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(content);
		StringBuffer sb = new StringBuffer();
		boolean result = m.find();
		while (result) {
			m.appendReplacement(sb, repStr);
			result = m.find();
		}
		m.appendTail(sb);
		return sb.toString();
	}

	

	public GenericPaginationManager<Blog, Long> getBlogManager() {
		return blogManager;
	}

	public void setBlogManager(GenericPaginationManager<Blog, Long> blogManager) {
		this.blogManager = blogManager;
	}

	public GenericPaginationManager<Article, Long> getArticleManager() {
		return articleManager;
	}

	public void setArticleManager(
			GenericPaginationManager<Article, Long> articleManager) {
		this.articleManager = articleManager;
	}

	public GenericPaginationManager<User, Long> getUserManager() {
		return userManager;
	}

	public void setUserManager(GenericPaginationManager<User, Long> userManager) {
		this.userManager = userManager;
	}

	public Blog getBlog() {
		return blog;
	}

	public void setBlog(Blog blog) {
		this.blog = blog;
	}

	public Article getArticle() {
		return article;
	}

	public void setArticle(Article article) {
		this.article = article;
	}

	public PaginationSupport getBlogPagination() {
		return blogPagination;
	}

	public void setBlogPagination(PaginationSupport blogPagination) {
		this.blogPagination = blogPagination;
	}

	public PaginationSupport getArticlePagination() {
		return articlePagination;
	}

	public void setArticlePagination(PaginationSupport articlePagination) {
		this.articlePagination = articlePagination;
	}

	public PaginationSupport getArticleCommentPagination() {
		return articleCommentPagination;
	}

	public void setArticleCommentPagination(
			PaginationSupport articleCommentPagination) {
		this.articleCommentPagination = articleCommentPagination;
	}

	public Long[] getBlogIds() {
		return blogIds;
	}

	public void setBlogIds(Long[] blogIds) {
		this.blogIds = blogIds;
	}

	public Long getBlogId() {
		return blogId;
	}

	public void setBlogId(Long blogId) {
		this.blogId = blogId;
	}

	public String getBloggerName() {
		return bloggerName;
	}

	public void setBloggerName(String bloggerName) {
		this.bloggerName = bloggerName;
	}

	public Long getArticleId() {
		return articleId;
	}

	public void setArticleId(Long articleId) {
		this.articleId = articleId;
	}

	public Long getCreatorId() {
		return creatorId;
	}

	public void setCreatorId(Long creatorId) {
		this.creatorId = creatorId;
	}

	public Long getBlogerId() {
		return blogerId;
	}

	public void setBlogerId(Long blogerId) {
		this.blogerId = blogerId;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getAttachIdsStr() {
		return attachIdsStr;
	}

	public void setAttachIdsStr(String attachIdsStr) {
		this.attachIdsStr = attachIdsStr;
	}

	public String getAllTagNames() {
		return allTagNames;
	}

	public void setAllTagNames(String allTagNames) {
		this.allTagNames = allTagNames;
	}

	public Long getPreviousArticleId() {
		return previousArticleId;
	}

	public void setPreviousArticleId(Long previousArticleId) {
		this.previousArticleId = previousArticleId;
	}

	public Long getNextArticleId() {
		return nextArticleId;
	}

	public void setNextArticleId(Long nextArticleId) {
		this.nextArticleId = nextArticleId;
	}

	public List<Article> getStatarticles() {
		return statarticles;
	}

	public void setStatarticles(List<Article> statarticles) {
		this.statarticles = statarticles;
	}

	public List<Long> getArticleIds() {
		return articleIds;
	}

	public void setArticleIds(List<Long> articleIds) {
		this.articleIds = articleIds;
	}

	public ArticleComment getArticleComment() {
		return articleComment;
	}

	public void setArticleComment(ArticleComment articleComment) {
		this.articleComment = articleComment;
	}

	public String[] getUserFacesCn() {
		return userFacesCn;
	}

	public void setUserFacesCn(String[] userFacesCn) {
		this.userFacesCn = userFacesCn;
	}

	public String[] getUserFacesEn() {
		return userFacesEn;
	}

	public void setUserFacesEn(String[] userFacesEn) {
		this.userFacesEn = userFacesEn;
	}

	public List<Tag> getLinkedTags() {
		return linkedTags;
	}

	public void setLinkedTags(List<Tag> linkedTags) {
		this.linkedTags = linkedTags;
	}
	public TopStep getTopStep() {
		return topStep;
	}
	public void setTopStep(TopStep topStep) {
		this.topStep = topStep;
	}
	
	public int getPageSize()
	{
		return pageSize;
	}
	public void setPageSize(int pageSize)
	{
		this.pageSize = pageSize;
	}

}
